package com.hqq.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * ReflectionUtil
 * 反射工具类
 * 用来创建类实例,调用类方法,设置类属性值
 * Created by heqianqian on 2017/7/19.
 */
public class ReflectionUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class);

    /**
     * 获取类实例
     *
     * @param clazz 类class
     * @return 实例
     */
    public static Object getInstance(Class<?> clazz) {
        Object instance = null;
        try {
            instance = clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        }
        return instance;
    }

    /**
     * 反射调用方法
     *
     * @param object 目标对象
     * @param method 目标方法
     * @param args   参数
     * @return Object
     */
    public static Object invokeMethod(Object object, Method method, Object... args) {
        Object result = null;
        try {
            method.setAccessible(true);
            result = method.invoke(object, args);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        }
        return result;
    }

    /**
     * 设置属性值
     *
     * @param object 目标对象
     * @param field  目标字段
     * @param value  属性值
     */
    public static void setField(Object object, Field field, Object value) {
        try {
            field.setAccessible(true);
            field.set(object, value);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}
